from decimal import Decimal
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext, ugettext_lazy as _
from l10n.utils import moneyfmt
from satchmo_store.shop.models import Order
from django.contrib.auth.models import *
from ocms.eventmanager.models import *
from ocms.merch.owasp_payments.processor import PaymentProcessor

from ocms.merch.listeners import EmailOnBilledStatus
from satchmo_store.shop import signals
import logging

logging.debug('mark was here ...... ')
signals.satchmo_order_status_changed.connect(EmailOnBilledStatus, sender=None)


class OWASPPayment(models.Model):
    order = models.OneToOneField(Order)
    method = models.CharField(verbose_name='Payment Method', max_length=100, editable="True", null=True, blank=True)
    event = models.OneToOneField(Event, blank=True, null=True)
    chapter = models.CharField(verbose_name='Chapter Name', max_length=512, editable="True", null=True, blank=True)
    balance = models.DecimalField(_("Outstanding Balance"),
        max_digits=18, decimal_places=10, blank=True, null=True)
    paydate = models.DateField(_('Paid on'), blank=True, null=True)
    authorizedby = models.OneToOneField(User, editable="False", null=True, blank=True)
    notes = models.TextField(_('Notes'), blank=True, null=True)
    
    def __unicode__(self):
        return "OWASP Order: #%s" % self.id

    def balance_due(self):
        if self.balance:
            b = self.balance
        else:
            b = Decimal('0.00')
            
        return moneyfmt(b)

    def order_link(self):
        return mark_safe(u'<a href="/admin/shop/order/%i/">%s #%i (%s)</a>' % (
            self.order.id,
            ugettext('Order'), 
            self.order.id, 
            moneyfmt(self.order.total)))
            
    order_link.allow_tags = True
    
    def save(self):
        if self.balance is None:
            self.balance = self.order.balance
        super(OWASPPayment, self).save()
        
    def authorize(self, user):
        #forces a payment authorization for this order
        auth = self.order.authorizations.filter(complete=False)[0]
        pp = PaymentProcessor()
        PaymentProcessor.capture_authorized_payment(PaymentProcessor=pp, authorization=auth, testing=False, order=self.order, amount=auth.amount)
        self.authorizedby = user
        balance = 0.00

import config
PAYMENT_PROCESSOR=True